package android.appinterfaces;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.util.Xml;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class StatisticActivity extends Activity{
	/** Called when the activity is first created. */
	private ImageView image;
    private Bitmap loadedImage;
    private String contents;
    private String food_txt= "";
    private Calendar c;
    private TextView tc;
    private TextView tcal1;
    private TextView tcal2;
    private LinearLayout fondo;
    private String[] fechas;
    private String[] calorias;
    private TextView nom;
    private TextView titStat;
    File a;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.statistic);
    	
        fechas=new String[7];
        calorias=new String[7];
        for (int k=0;k<7;k++){
        	fechas[k]="";
        	calorias[k]="";
        }
        tc = (TextView) findViewById(R.id.textcom2);
        tcal1 = (TextView) findViewById(R.id.textCons);
        tcal2 = (TextView) findViewById(R.id.textRest);
        nom = (TextView) findViewById(R.id.textNom);
        titStat = (TextView) findViewById(R.id.textVStat);
        image = (ImageView) findViewById(R.id.graphic);
        fondo = (LinearLayout) findViewById(R.id.linearLayout4);
        updateStatistic();
        Button b=(Button) findViewById(R.id.btnQR);
        b.setOnClickListener(new OnClickListener(){
    		@Override
    		public void onClick(View v) {
    				// TODO Auto-generated method stub
    			Intent intent = new Intent("com.google.zxing.client.android.SCAN");
    		        intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
    		        startActivityForResult(intent, 0);
    		}
     
        });
        
        Button b2=(Button) findViewById(R.id.btnHist);
        b2.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent v=new Intent(StatisticActivity.this,HistorialActivity.class);
				startActivity(v);
			}
		});
        

    }
    
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
	 	   if (requestCode == 0) {
	 	      if (resultCode == RESULT_OK) {
	 	         contents = intent.getStringExtra("SCAN_RESULT");
	 	         // Handle successful scan
	 	         // Guardamos un xml con la ultima comida y las calorias actuales
	 	         buildFood(contents);

	 	         updateStatistic();

	 	      } else if (resultCode == RESULT_CANCELED) {
	 	         // Handle cancel
	 	      }
	 	   }
	}
    public String readFood(){ 
    	String s; 
    	String t = ""; 
    	try{
    		File ruta_sd = Environment.getExternalStorageDirectory();
    		File a = new File(ruta_sd.getAbsolutePath(), "comida.txt");
    		FileReader reader = new FileReader(a);
    		BufferedReader bf = new BufferedReader(reader);
    		while((s=bf.readLine())!=null) t = t + s; ;
    	}
    	catch (Exception ex){
    		Toast adv = Toast.makeText(getApplicationContext(), "Error inesperado al leer el archivo comida.txt", Toast.LENGTH_SHORT);
    		adv.show();
    		t = "";
    	}
    	return t;
    }
    
    public String readUser(){
    	int indice1, indice2;
    	String salida = "";
    	String auxiliar1, auxiliar2, auxiliar3;
    	String t = "";
    	File ruta_sd = Environment.getExternalStorageDirectory();
		File a = new File(ruta_sd.getAbsolutePath(), "usuarios.xml");
		try {
			BufferedReader entrada = new BufferedReader(new FileReader(a));
			try {
				while ((t = entrada.readLine())!=null){
					salida = salida + t;
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				Toast adv = Toast.makeText(getApplicationContext(), "Error al leer usuarios.xml", Toast.LENGTH_SHORT);
	    		adv.show();
			}
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			Toast adv = Toast.makeText(getApplicationContext(), "No se encuentra usuarios.xml", Toast.LENGTH_SHORT);
    		adv.show();
		}
		
		indice1 = salida.indexOf("<calorias>");
		indice2 = salida.indexOf("</calorias>");
		auxiliar1 = salida.substring(indice1+10, indice2);
		
		indice1 = salida.indexOf("<nombre>");
		indice2 = salida.indexOf("</nombre>");
		auxiliar2 = salida.substring(indice1+8, indice2); 
		
		salida = auxiliar2 + "-" + auxiliar1;
		return salida;
    }
    
    public void buildFood(String food){  
    	/* Creamos el archivo */
    	String []tuser =null;
    	String u = readUser();
    	tuser = u.split("-");
    	String []f = food.split("-");
    	int calact = Integer.parseInt(tcal1.getText().toString());
    	int caltot = Integer.parseInt(tuser[1]);
    	c = Calendar.getInstance();
    	int dia = c.get(Calendar.DATE);
    	calact = calact + Integer.parseInt(f[1]);
    	int rest = caltot-calact;
    	if (rest < 0){
    		food_txt = Integer.toString(dia)+"-"+f[0]+"-"+(Integer.toString(calact))+"-"+"exceso";
    	}else{
    		food_txt = Integer.toString(dia)+"-"+f[0]+"-"+(Integer.toString(calact))+"-"+"bien";
    	}
    	try{
    		File ruta_sd = Environment.getExternalStorageDirectory();
    		File a = new File(ruta_sd.getAbsolutePath(), "comida.txt");
    		OutputStreamWriter fout = new OutputStreamWriter(new FileOutputStream(a));
    		fout.write(food_txt);
    		fout.close();
    		Toast adv = Toast.makeText(getApplicationContext(), "Ultima comida guardada.", Toast.LENGTH_SHORT);
    		adv.show();
    	}
    	catch (Exception ex){
    	}
    }
    public void updateStatistic(){
    	String mUrl = "";
    	String []textuser =null;
    	String []texto=null;
    	String text = readFood();
    	String user = readUser();
    	if(user.length()!=0){
    		textuser = user.split("-");
    		nom.setText(textuser[0]);
    		tcal2.setText(textuser[1]);
    	}
    	if(text.length()!=0){
    		texto=text.split("-");
        	c = Calendar.getInstance();
            if(!texto[0].equals(Integer.toString(c.get(Calendar.DATE)))){
            	try{
    	        	food_txt="";
    	        	File ruta_sd = Environment.getExternalStorageDirectory();
    	    		File a = new File(ruta_sd.getAbsolutePath(), "comida.txt");
    	    		OutputStreamWriter fout = new OutputStreamWriter(new FileOutputStream(a));
    	    		fout.write(food_txt);
    	    		fout.close();
    	    		readXml(texto[0],texto[2]);
    	    	}catch(Exception ex){
                }
            	
            }
    	}
        text=readFood();    	
        if (text.length() == 0){
        	fondo.setBackgroundResource(R.color.green);
        	tc.setText("Vacio");
        	tcal1.setText("0");
        	mUrl = "https://chart.googleapis.com/chart?cht=p3&chs=400x150&chd=t:100&chl=Restantes&chco=0000FF&chf=bg,s,9FFF92";
        }else{
        	texto = text.split("-");
        	tc.setText(texto[1]);
        	if(texto[3].equals("exceso")){
        		tcal1.setText(texto[2]);
        		fondo.setBackgroundResource(R.color.red);
        		tcal2.setText("Se ha pasado de ");
        		mUrl = "https://chart.googleapis.com/chart?cht=p3&chs=400x150&chd=t:100&chl=Consumidas&chco=0000FF&chf=bg,s,FE8888";
        	}else{
        		int caltot = Integer.parseInt(tcal2.getText().toString());
        		tcal1.setText(texto[2]);
            	int calcons = Integer.parseInt(texto[2]);
            	int calrest = caltot-calcons;
            	tcal2.setText(Integer.toString(calrest));
            	int percent1 = (calcons*100)/(calcons+calrest);
            	int percent2 = (calrest*100)/(calcons+calrest);
            	mUrl = "https://chart.googleapis.com/chart?cht=p3&chs=400x150&chd=t:"+Integer.toString(percent2)+","+Integer.toString(percent1)+"&chl=Restantes|Consumidas&chco=0000FF&chf=bg,s,9FFF92";
        	}
        }  
        downloadFile(mUrl);
             
    }
    
    void downloadFile(String imageHttpAddress) {
        URL imageUrl = null;
        try {
            imageUrl = new URL(imageHttpAddress);
            HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
            conn.connect();
            loadedImage = BitmapFactory.decodeStream(conn.getInputStream());
            image.setImageBitmap(loadedImage);
        } catch (IOException e) {
            Toast.makeText(getApplicationContext(), "Error cargando la imagen: "+e.getMessage(), Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }
    
    public void readXml(String dia, String calT){
    	int indice1, indice2;
    	String salida = "";
    	String auxiliar1, auxiliar2, auxiliar3;
    	String t = "";
    	File ruta_sd = Environment.getExternalStorageDirectory();
		File a = new File(ruta_sd.getAbsolutePath(), "historial.xml");
		try {
			BufferedReader entrada = new BufferedReader(new FileReader(a));
			try {
				while ((t = entrada.readLine())!=null){
					salida = salida + t;
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
			}
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			//Toast adv = Toast.makeText(getApplicationContext(), "No se encuentra usuarios.xml", Toast.LENGTH_SHORT);
    		//adv.show();
		}
		
		int num=0,indice=0;
		try{
			if(salida.indexOf("<fecha1>")!=-1){
				indice1 = salida.indexOf("<fecha1>");
				indice2 = salida.indexOf("</fecha1>");
				fechas[0] = salida.substring(indice1+8, indice2);
			}
			if(salida.indexOf("<fecha2>")!=-1){
				indice1 = salida.indexOf("<fecha2>");
				indice2 = salida.indexOf("</fecha2>");
				fechas[1] = salida.substring(indice1+8, indice2);
			}
			if(salida.indexOf("<fecha3>")!=-1){
				indice1 = salida.indexOf("<fecha3>");
				indice2 = salida.indexOf("</fecha3>");
				fechas[2] = salida.substring(indice1+8, indice2);
			}
			if(salida.indexOf("<fecha4>")!=-1){
				indice1 = salida.indexOf("<fecha4>");
				indice2 = salida.indexOf("</fecha4>");
				fechas[3] = salida.substring(indice1+8, indice2);
			}
			if(salida.indexOf("<fecha5>")!=-1){
				indice1 = salida.indexOf("<fecha5>");
				indice2 = salida.indexOf("</fecha5>");
				fechas[4] = salida.substring(indice1+8, indice2);
			}
			if(salida.indexOf("<fecha6>")!=-1){
				indice1 = salida.indexOf("<fecha6>");
				indice2 = salida.indexOf("</fecha6>");
				fechas[5] = salida.substring(indice1+8, indice2);
			}
			if(salida.indexOf("<fecha7>")!=-1){
				indice1 = salida.indexOf("<fecha7>");
				indice2 = salida.indexOf("</fecha7>");
				fechas[6] = salida.substring(indice1+8, indice2);
			}
			if(salida.indexOf("<calorias1>")!=-1){
				indice1 = salida.indexOf("<calorias1>");
				indice2 = salida.indexOf("</calorias1>");
				calorias[0] = salida.substring(indice1+11, indice2);
				num++;
			}
			if(salida.indexOf("<calorias2>")!=-1){
				indice1 = salida.indexOf("<calorias2>");
				indice2 = salida.indexOf("</calorias2>");
				calorias[1] = salida.substring(indice1+11, indice2);
				num++;
			}
			if(salida.indexOf("<calorias3>")!=-1){
				indice1 = salida.indexOf("<calorias3>");
				indice2 = salida.indexOf("</calorias3>");
				calorias[2] = salida.substring(indice1+11, indice2);
				num++;
			}
			if(salida.indexOf("<calorias4>")!=-1){
				indice1 = salida.indexOf("<calorias4>");
				indice2 = salida.indexOf("</calorias4>");
				calorias[3] = salida.substring(indice1+11, indice2);
				num++;
			}
			if(salida.indexOf("<calorias5>")!=-1){
				indice1 = salida.indexOf("<calorias5>");
				indice2 = salida.indexOf("</calorias5>");
				calorias[4] = salida.substring(indice1+11, indice2);
				num++;
			}
			if(salida.indexOf("<calorias6>")!=-1){
				indice1 = salida.indexOf("<calorias6>");
				indice2 = salida.indexOf("</calorias6>");
				calorias[5] = salida.substring(indice1+11, indice2);
				num++;
			}
			if(salida.indexOf("<calorias7>")!=-1){
				indice1 = salida.indexOf("<calorias7>");
				indice2 = salida.indexOf("</calorias7>");
				calorias[6] = salida.substring(indice1+11, indice2);
				num++;
			}
			indice1=salida.indexOf("<i>");
			indice2=salida.indexOf("</i>");
			indice=Integer.parseInt(salida.substring(indice1+3,indice2));
		}catch(Exception e){
			
		}
	    	
			if(num<7){
		        fechas[num]=dia;
		        calorias[num]=calT;
			}else{
				fechas[indice%7]=dia;
		        calorias[indice%7]=calT;
		        indice++;
			}
	        
	        String historial_xml = 
					"<?xml version='1.0' encoding='UTF-7' ?>" +
					"<historial>";
	        int ind=1,i=0,j=0,aux;
	        if(num<7){aux=0; num++;indice++;}
	        else aux=indice%7;
	        for(j=aux;j<num;j++){
	        	historial_xml=historial_xml+"<dia>" +
	        									"<fecha"+ind+">" + fechas[j] + "</fecha"+ind+">" +
	        									"<calorias"+ind+">" + calorias[j] + "</calorias"+ind+">" +
	        								"</dia>";
	        	ind++;
	        }
	        if(num==7){
		        for(j=0;j<aux;j++){
		        	historial_xml=historial_xml+"<dia>" +
		        									"<fecha"+ind+">" + fechas[j] + "</fecha"+ind+">" +
		        									"<calorias"+ind+">" + calorias[j] + "</calorias"+ind+">" +
		        								"</dia>";
		        	ind++;
		        }
	        }
        	historial_xml=historial_xml + "<i>" + indice + "</i>" + "</historial>";
				/* Guardamos el xml */
				
				try
				{
				    ruta_sd = Environment.getExternalStorageDirectory();
				    File f = new File(ruta_sd.getAbsolutePath(), "historial.xml");
				    OutputStreamWriter fout = new OutputStreamWriter(new FileOutputStream(f));
				    fout.write(historial_xml);
				    fout.close();
				}
				catch (Exception ex)
				{
					Toast adv = Toast.makeText(getApplicationContext(), "Error inesperado al guardar el usuario", Toast.LENGTH_SHORT);
				    adv.show();
				}
    }
}
